import _ from 'lodash'
import { v4 } from 'uuid'
import type { Dictionary } from '../define/types'

export const primaryKey = (): string => {
  return 'id'
}

export const v4Id = (): string => {
  return v4().toLocaleLowerCase().replace(/-/g, '')
}

export const sqliteTypes = [
  'TEXT',
  'INTEGER',
  'REAL',
  'BLOB',
  'NULL',
  'BOOLEAN',
  'JSON'
]

export const jsToSqliteType = (value: any): string => {
  if (_.isString(value)) {
    return 'TEXT'
  } else if (_.isBoolean(value) || _.isNumber(value)) {
    return _.isInteger(value) ? 'INTEGER' : 'REAL'
  } else if (Buffer.isBuffer(value)) {
    return 'BLOB'
  } else if (_.isObject(value) || _.isArray(value)) {
    return 'JSON'
  } else {
    return 'NULL'
  }
}

export const toSqliteTypes = (data: any): Dictionary => {
  const mapping: Dictionary = {}
  _.entries(data).forEach(([k, v]) => {
    mapping[k] = jsToSqliteType(v)
  })
  return mapping
}

export const isMediaUrl = (url: string) => {
  if (!_.isString(url)) {
    return 'text'
  }
  if (url.match(/\.(jpeg|jpg|gif|png)$/) != null) {
    return 'image'
  } else if (url.match(/\.(mp4|webm|ogg)$/) != null) {
    return 'video'
  } else if (url.match(/\.(mp3|wav|ogg)$/) != null) {
    return 'audio'
  } else if (url.startsWith('http')) { 
    return 'link'
  }
  return 'text'
}